package com.zl.controller;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.sun.javafx.binding.IntegerConstant;
import com.zl.util.Util;
import net.sf.json.JSONObject;

import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.zl.domain.Query;
import com.zl.domain.User;
import com.zl.service.UserService;

import java.io.IOException;
import java.util.Map;

@Controller
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping(value = "/toIndex", method = RequestMethod.GET)
    public ModelAndView toIndex(HttpServletResponse response) {
        return new ModelAndView("/index");
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public ModelAndView toLogin() {
        return new ModelAndView("/login");
    }

    @RequestMapping(value = "/user/logout", method = RequestMethod.GET)
    public void logout(HttpSession session, HttpServletResponse response, HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null)
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("atlg")) {
                    cookie.setValue(null);
                    cookie.setPath("/");
                    cookie.setMaxAge(0);
                    response.addCookie(cookie);
                }
            }
        if (session.getAttribute("user") != null) {
            Map<String, Object> userMap = ((Map<String, Object>) session.getAttribute("user"));
            User user = new User();
            user.setUsername(userMap.get("username") + "");
            user.setAutoLogin(-1);
            user.setId(Integer.parseInt(userMap.get("id") + ""));
            userService.update(user);
            session.removeAttribute("user");
        }
        try {
            response.sendRedirect(request.getContextPath() + "/login");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/user/login", method = RequestMethod.POST)
    public
    @ResponseBody
    JSONObject login(@Param("User") User user, HttpServletResponse response, HttpSession session) {
        int autoLogin = user.getAutoLogin();
        Map<String, Object> userMap = userService.login(user);
        if (userMap != null) {
            if (autoLogin == 1) {
                user.setAutoLogin(1);
                userService.update(user);
                Cookie cookie = new Cookie("atlg", user.getUsername() + Util.md5(",;.") + Util.md5("cnmlgb"));
                cookie.setPath("/");
                cookie.setMaxAge(7 * 24 * 3600);
                response.addCookie(cookie);
            }
            userMap.put("privileges", userService.findPrivileges(userMap.get("rid") + ""));
            session.setAttribute("user", userMap);
        }
        return new JSONObject().accumulate("hide", userMap != null);
    }

    @RequestMapping(value = "/user/addUser", method = RequestMethod.GET)
    public
    @ResponseBody
    JSONObject addUser(@Param("User") User user) {
        return new JSONObject().accumulate("message",
                userService.insert(user) == 1 ? "添加成功！" : "添加失败！！");
    }

    @RequestMapping(value = "/user/userList", method = RequestMethod.GET)
    public
    @ResponseBody
    JSONObject userList(@Param("Query") Query query, HttpServletRequest request) {
        query.setPrivilegeWeight(((Map<String, Object>) request.getSession().getAttribute("user")).get("weight") + "");
        return new JSONObject().accumulate("page", userService.page(query));
    }

    @RequestMapping(value = "/user/delUser", method = RequestMethod.GET)
    public
    @ResponseBody
    JSONObject delUser(String username) {
        return new JSONObject().accumulate("message",
                userService.delUser(username) == 0 ? "删除失败！！" : "删除成功！");
    }

    @RequestMapping(value = "/user/updateUser", method = RequestMethod.POST)
    public
    @ResponseBody
    JSONObject updateUser(@Param("User") User user, HttpServletRequest request, HttpServletResponse response) {
        boolean success = userService.update(user) != 0;
        if (success) {
            Cookie[] cookies = request.getCookies();
            if (cookies != null)
                for (Cookie cookie : cookies)
                    if (cookie.getName().equals("atlg")) {
                        cookie.setValue(null);
                        cookie.setPath("/");
                        cookie.setMaxAge(0);
                        response.addCookie(cookie);
                    }
        }
        return new JSONObject().accumulate("message",
                !success ? "修改失败！！" : "修改成功！");
    }

    @RequestMapping(value = "/user/curUser", method = RequestMethod.GET)
    public
    @ResponseBody
    JSONObject curUser(HttpServletRequest request) {
        return new JSONObject().accumulate("user", request.getSession().getAttribute("user"));
    }

    @RequestMapping(value = "/user/check", method = RequestMethod.GET)
    public
    @ResponseBody
    JSONObject check(User user) {
        return new JSONObject().accumulate("valid", userService.findUser(user) == null);
    }

    @RequestMapping(value = "/user/getPrivileges", method = RequestMethod.GET)
    public
    @ResponseBody
    JSONObject getPrivileges(HttpServletRequest request) {
        Map<String, Object> userMap = ((Map<String, Object>) request.getSession().getAttribute("user"));
        return new JSONObject().accumulate("privileges", userMap != null ? userService.findPrivileges(userMap.get("rid") + "") : "");
    }

}
